var clientTable = {};
var clientStatusOption = [{id: '99', text: '待审核'}, {id: '00', text: '审核中'}, {id: '01', text: '审核通过'}, {id: '02', text: '审核驳回'}];
var clientTypeOption=[{id: '01', text: '操作代理绑定'}, {id: '02', text: '航司绑定'}];
const blackDelflagObj = {
    '': {
        title: "有效",
        class: " m-badge--success"
    },
    '2': {
        title: "有效",
        class: " m-badge--success"
    },
    '1': {
        title: "黑名单",
        class: " m-badge--danger"
    }
};

const clientStatusObj = {
    '99': {
        title: "待审核",
        class: "m-badge--metal"
    },
    '00': {
        title: "审核中",
        class: "m-badge--warning"
    },
    '01': {
        title: "审核通过",
        class: "m-badge--success"
    },
    '02': {
        title: "审核驳回",
        class: "m-badge--danger"
    }
};

$(function () {
    //表单搜索
    searchFormInit();
    //事件注册
    bindingEvent();
    //表格初始化
    tableInit(getSearchData());
});

/**
 * 表单搜索
 */
function searchFormInit() {
    //市场部审核状态
    $("#clientStatus").select2({
        placeholder: "市场部审核状态",
        data: clientStatusOption,
        allowClear: true
    });
}

/**
 * 事件注册
 */
function bindingEvent() {
    // 重置按钮
    $("#m_reset").on("click", function () {
        $('#cFullname').val('').triggerHandler("click");
        $('#clientStatus').val('').change();
        $('#clientNcstatus').val('').change();
    });

    // 查询按钮
    $("#m_search").on("click", function () {
        queryMDatatable(clientTable, getSearchData());
    });

    //编辑
    $('#m_edit').on('click', function () {
        let ids = getMDatatableSelectedIds(clientTable);
        if (ids.length != 1) {
            return alertMsg('请选中一条记录');
        }
        let row = getMDatatableRow(clientTable, ids[0], 'id');
        if (row.clientStatus == '00') {
            alertMsg('客户信息审核中，不可修改！');
            return false
        }else if (row.clientStatus == '01') {
            alertMsg('客户信息审核通过，不可修改！');
            return false
        }
        layer.open({
            title: '客户修改',
            type: 2,
            maxmin: true,
            area: ['100%', '100%'],
            content: `${basePath}/hcChrgClient/addorupdate/${ids[0]}`,
        });
    });

    //点击查看
    $("#client-table").on('click', '.cFullname', function () {
        let id = $(this).parent().find("td:first-child [type='checkbox']").val();
        if (isNotEmpty(id)) {
            layer.open({
                title: '详情',
                type: 2,
                maxmin: true,
                area: ['100%', '100%'],
                content: `${basePath}/hcChrgClient/detail/${id}`,
            });
        }
    }).on('click', '.backReason', function () {
        let id = $(this).parent().find("td:first-child [type='checkbox']").val();
        if (isNotEmpty(id)) {
            let backReasons = getClientBackflowByCid(id);
            layer.open({
                title: '市场部回执',
                type: 1,
                area: ['80%', '80%'],
                btn: ['关闭'],
                content: $("#responseHtml").html(),
                success: function (layero, index) {
                    loadResponseMsg(backReasons);
                },
                yes: function (index, layero) {
                    layer.closeAll();
                }
            });
        }
    });

    /**
     * 删除
     */
    $('#m_delete').on('click', function () {
        let ids = getMDatatableSelectedIds(clientTable);
        if (ids.length == 0) {
            return alertMsg('请至少选中一条记录')
        }
        for (let i = 0; i < ids.length; i++) {
            let row = getMDatatableRow(clientTable,ids[i],'id');
            if (row.clientStatus == '01') {
                alertMsg('客户信息审核通过，不可删除！');
                return false
            }else if (row.clientStatus == '00') {
                alertMsg('客户信息审核中，不可删除！');
                return false
            }
        }
        let lock = false;//默认未锁定
        layer.confirm('删除操作会<font color="red">删除记录和已上传的附件</font>,是否继续', {
            icon: 3,
            title: '提示',
            btn: ['确定', '取消'] // 按钮
        }, function () {
            if (!lock) {
                lock = true;//锁定，防止快速点击触发多次提交
                layer.msg('删除中...', {
                    time: '-1'
                });
                $.hcPostAjax({
                    url: basePath + '/hcChrgClient/' + ids,
                    type: 'delete',
                    success: function (json) {
                        layer.msg('删除成功!', {icon: 1, time: 1500}, function () {
                            $("#m_search").triggerHandler('click');
                            layer.closeAll();
                        });
                    }
                });
            }
        }, function (index) {
            layer.close(index);
        });
    });

    /**
     * 绑定
     */
    $('#u_agentOrCarrier').on('click', function () {
        var ids = getMDatatableSelectedIds(clientTable);
        if (ids.length != 1) {
            return alertMsg('请选中一条记录');
        }
        layer.open({
            title: '绑定',
            type: 1,
            maxmin: true,
            area: ['60%', '60%'],
            shadeClose: true,
            scrolling:false,
            content: $("#agentOrCarrierHtml").html(),
            success: function(layero, index) {
                loadAllAgent();
                loadAllCarrier();
                loadClientType();
                //渲染old数据
                var agentCarriers=getUAgentCarrier(ids[0]);
                if(agentCarriers){
                    renderFormData("#agentOrCarrier-form", agentCarriers);
                    if(agentCarriers.clientType && agentCarriers.clientType =='01'){
                        $("#agentcodeDiv").show();
                    }else if(agentCarriers.clientType && agentCarriers.clientType =='02'){
                        $("#carrierDiv").show();
                    }
                }
                //保存
                $("#save_agentCarrier").on("click", function () {
                    var param = {};
                    param.id = ids[0];
                    param.clientType = $.trim($("select[name=clientType]").val());
                    param.agentcode = $.trim($("select[name=agentcode]").val());
                    param.carrier = $.trim($("select[name=carrier]").val());
                    $.hcPostAjax({
                        showLoad: true,
                        url: basePath + '/hcChrgClient/uAgentCarrier',
                        msgPrefix: "绑定出错：",
                        type: 'post',
                        data: param,
                        success: function (data) {
                            layer.msg('绑定成功！', {
                                icon: 1, time: 1500
                            }, function () {
                                $("#m_search").triggerHandler('click');
                                layer.closeAll();
                            });
                        }
                    });
                });
                //取消
                $("#cancel_agentCarrier").on("click", function() {
                    layer.closeAll();
                });
            }
        });
    });

}

//表格初始化
function tableInit(searchData = null) {
    let tableColumns = [
        {field: "id", title: "#", width: 10, textAlign: 'center', selector: {
                class: "m-checkbox--solid m-checkbox--brand"
            }},
        {field: "blackDelflag", textAlign: 'center', title: "状态", titleHide: true, width: 80,
            template: function (t) {
                return '<span class="m-badge ' + blackDelflagObj[t.blackDelflag].class + ' m-badge--wide">' + blackDelflagObj[t.blackDelflag].title + "</span>"
            }},
        {field: "clientStatus", title: "审核状态", textAlign: 'center', titleHide: true, width: 80,class: 'clientStatus',
            template: function (t) {
                if (isEmpty(t.clientStatus)) return '';
                return '<span class="m-badge ' + clientStatusObj[t.clientStatus].class + ' m-badge--wide">' + clientStatusObj[t.clientStatus].title + "</span>"
            }},
        {field: "backReason", title: '驳回原因（<font color="red">点击查看驳回详情</font>）', textAlign: 'center', width: 200,class: 'backReason', titleHide: true,
            template: function (t) {
                let value = '-';
                let title = '-';
                if (!isEmpty(t.backReason)){
                    value = t.backReason;
                    title = t.backReason;
                }
                return "<span title='" + title +"'>" + value + "</span>";
            }},
        {field: "cFullname", textAlign: 'center', title: '客户全称（<font color="red">点击查看客户详情</font>）', width: 220,class: 'cFullname',titleHide: true,
            template: function (row) {
                let value = row.cFullname;
                let title = row.cFullname;
                return "<span title='" + title +"'>" + value + "</span>";
            }},
        {field: "cLinkman", textAlign: 'center', title: "联系人", width: 80},
        {field: "cTele", textAlign: 'center', title: "联系电话", width: 90},
        {field: "iName", textAlign: 'center', title: "发票抬头", width: 220},
        {field: "iTaxno", textAlign: 'center', title: "税号", width: 150},
        {field: "clientType", title: "绑定类型", textAlign: 'center', titleHide: true, width: 80,
            template: function (t) {
                if (t.clientType && t.clientType=='01') {
                    return '操作人';
                } else if(t.clientType && t.clientType=='02') {
                    return '航司';
                } else {
                    return '';
                }
            }
        },
        {field: "agentcarrier", textAlign: 'center', title: "绑定", width: 80},
        {field: "userid", textAlign: 'center', title: "登陆账号", width: 80}];

    let mDatatableOption = getMDatatableOption("list", searchData, tableColumns);
    mDatatableOption["rows"] = {
        afterTemplate: function (row, data, index) {
            let id = data.id;
            if (data.blackDelflag == '1') {
                $("#client-table td[title=" + id + "]").parent().children().css("background-color", "rgb(253 164 164)");
            }
        }
    };
    clientTable = $("#client-table").mDatatable(mDatatableOption);
}

/**
 * 搜索条件
 * @returns {{}}
 */
function getSearchData() {
    var result = {
        'cFullname': $.trim($('#cFullname').val()),
        'clientStatus': $.trim($('#clientStatus').val())
    };
    return result;
}

//加载客户类型
function loadClientType(){
    //初始化
    $("#carrier").val('').change();
    $("#carrierDiv").hide();
    $("#agentcode").val('').change();
    $("#agentcodeDiv").hide();
    //绑定
    $("#clientType").select2({
        placeholder: "请选择绑定类型",
        data: clientTypeOption,
        allowClear: false
    }).on("select2:close", function () {
        if(isEmpty($(this).val())){
            $("#carrier").val('').change();
            $("#carrierDiv").hide();
            $("#agentcode").val('').change();
            $("#agentcodeDiv").hide();
        }else{
            if(!isEmpty($(this).val()) && $(this).val()=='01') {
                $("#carrier").val('').change();
                $("#carrierDiv").hide();
                $("#agentcodeDiv").show();
            }else{
                $("#agentcode").val('').change();
                $("#agentcodeDiv").hide();
                $("#carrierDiv").show();
            }
        }
    });
}

//加载全部承运人
function loadAllCarrier() {
    $.hcPostAjax({
        async: false,
        url: basePath + '/carriers',
        type: 'get',
        data: {
            pagenation: false
        },
        success: function (json){
            var carrierOption = [];
            if (json) {
                $.each(json, function (i) {
                    carrierOption.push({
                        id: json[i].carrier + "",
                        text: json[i].carrier + "(" + json[i].namecn + ")"
                    });
                });
                //承运人
                $("#carrier").val('').select2({
                    placeholder: "请选择航司",
                    data: carrierOption,
                    multiple:true,
                    allowClear: false,
                    width: '100%'
                });
            }
        }
    });
}

//加载全部代理人
function loadAllAgent() {
    $.hcPostAjax({
        async: false,
        url: basePath + '/hcDicAgent',
        type: 'get',
        data: {
            pagenation: false,
            activestatus: '1'
        },
        success: function (json) {
            var agentOption = [];
            if (json) {
                $.each(json, function (i) {
                    agentOption.push({
                        id: json[i].agentcode + "",
                        text: json[i].agentcode + "(" + json[i].namecn + ")"
                    });
                });
                //货代
                $("select[name=agentcode]").val('').select2({
                    placeholder: "请选择代理人",
                    data: agentOption,
                    multiple:true,
                    allowClear: false,
                    width: '100%'
                });
            }
        }
    });
}

//获取客户管理货代航司
function getUAgentCarrier(id) {
    var oldData;
    $.hcPostAjax({
        type: 'get',
        url: basePath + '/hcChrgClient/getAgentcarrier',
        async: false,
        data: {
            id: id
        },
        success: function (data) {
            oldData = data;
        }
    });
    return oldData;
}

/**
 * 根据CID获取审核驳回流水信息
 * @param cid
 * @returns {string}
 */
function getClientBackflowByCid(cid) {
    let msg='';
    $.hcPostAjax({
        type: 'post',
        url: basePath + '/hcChrgClientBackflow/getClientBackflowByCid',
        async: false,
        data: {
            cid: cid,
        },
        success: function (json) {
            if (json) {
                $.each(json, function (i) {
                    msg = msg + json[i].opdate + "  " + json[i].backReason + "\n";
                });
            }
        }
    });
    return msg;
}

/**
 * 加载回执信息
 * @param row
 */
function loadResponseMsg(remark) {
    $('.response-form').find('textarea').val(remark);
}